package cn.xuchunh.campusbbs.utils;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xuchunh.campusbbs.bean.Forum;
import cn.xuchunh.campusbbs.bean.Reply;
import cn.xuchunh.campusbbs.bean.ReplyContent;
import cn.xuchunh.campusbbs.bean.SimpleData;
import cn.xuchunh.campusbbs.storage.sqlite.DBManager;

/**
 * Created by XuChunH on 2015/9/26.
 */
public class JsonParser {

    public static List<Forum> parseForumList(JSONObject jsonObject) {
        List<Forum> forumsList = new ArrayList<>();
        JSONArray list = jsonObject.optJSONArray(JsonKey.LIST);
        JSONObject categoryJson;
        JSONObject boardJson;
        for (int i = 0; i < list.length(); i++) {
            categoryJson = list.optJSONObject(i);
            JSONArray boardList = categoryJson.optJSONArray(JsonKey.BOARD_LIST);
            for (int j = 0; j < boardList.length(); j++) {
                Forum board = new Forum();
                boardJson = boardList.optJSONObject(j);
                board.setId(boardJson.optInt(JsonKey.BOARD_ID));
                board.setName(boardJson.optString(JsonKey.BOARD_NAME));
                board.setDesc(boardJson.optString(JsonKey.DESCRIPTION));
                board.setChild(boardJson.optInt(JsonKey.BOARD_CHILD) != 0);
                board.setIcon(boardJson.optString(JsonKey.BOARD_IMG));
                String lastPostDate = boardJson.optString(JsonKey.LAST_POSTS_DATE);
                if (!TextUtils.isEmpty(lastPostDate)) {
                    board.setLastPostsDate(Long.valueOf(lastPostDate));
                }
                board.setContent(boardJson.optInt(JsonKey.BOARD_CONTENT));
                board.setForumRedirect(boardJson.optString(JsonKey.FORUMREDIRECT));
                board.setTodayPostsNum(boardJson.optInt(JsonKey.TD_POSTS_NUM));
                board.setTopicTotalNum(boardJson.optInt(JsonKey.TOPIC_TOTAL_NUM));
                board.setPostsTotalNum(boardJson.optInt(JsonKey.POSTS_TOTAL_NUM));
                board.setFocus(boardJson.optInt(JsonKey.IS_FOCUS) != 0);
                forumsList.add(board);
            }
        }
        return forumsList;
    }

    public static List<Reply> parseReplyList(JSONArray replyArray, int topicId) {
        List<Reply> replyList = new ArrayList<>();
        JSONObject replyJson;
        int size = replyArray.length();
        for (int i = 0; i < size; i++) {
            Reply reply = new Reply();
            replyJson = replyArray.optJSONObject(i);
            reply.setUserId(replyJson.optInt(JsonKey.REPLY_ID));
            reply.setTopicId(topicId);
            reply.setType(replyJson.optString(JsonKey.REPLY_TYPE));
            reply.setName(replyJson.optString(JsonKey.REPLY_NAME));
            reply.setId(replyJson.optInt(JsonKey.REPLY_POSTS_ID));
            reply.setPosition(replyJson.optInt(JsonKey.POSITION));
            String date = replyJson.optString(JsonKey.POSTS_DATE);
            reply.setPostsDate(TextUtils.isEmpty(date) ? 0 : Long.valueOf(date));
            reply.setAvatar(replyJson.optString(JsonKey.ICON));
            reply.setLevel(replyJson.optInt(JsonKey.LEVEL));
            reply.setUserTitle(replyJson.optString(JsonKey.USERTITLE));
            reply.setLocation(replyJson.optString(JsonKey.LOCATION));
            reply.setMobileSign(replyJson.optString(JsonKey.MOBILESIGN));
            reply.setReplyStaus(replyJson.optInt(JsonKey.REPLY_STATUS));
            reply.setStatus(replyJson.optInt(JsonKey.STATUS));
            reply.setRoleNum(replyJson.optInt(JsonKey.ROLE_NUM));
            reply.setTitle(replyJson.optString(JsonKey.TITLE));
            reply.setQuote(replyJson.optInt(JsonKey.IS_QUOTE) != 0);
            reply.setQuotePid(replyJson.optInt(JsonKey.QUOTE_PID));
            reply.setQuoteContent(replyJson.optString(JsonKey.QUOTE_CONTENT));
            reply.setQuoteUserName(replyJson.optString(JsonKey.QUOTE_USER_NAME));

            JSONArray contentArray = replyJson.optJSONArray(JsonKey.REPLY_CONTENT);
            parseReplyContent(contentArray, reply);

            replyList.add(reply);

        }

        return replyList;
    }

    private static void parseReplyContent(JSONArray contentArray, Reply reply) {
        JSONObject contentJson;
        int size = contentArray.length() > 2 ? 2 : contentArray.length();
        for (int i = 0; i < size; i++) {
            ReplyContent content = new ReplyContent();
            contentJson = contentArray.optJSONObject(i);
            content.setInfo(contentJson.optString(JsonKey.INFOR));
            content.setType(contentJson.optInt(JsonKey.TYPE));
            content.setUrl(contentJson.optString(JsonKey.URL));
            content.setOriginalInfo(contentJson.optString(JsonKey.ORIGINALINFO));
            content.setAid(contentJson.optInt(JsonKey.AID));
            if (content.getType() == ReplyContent.TYPE_VIDEO) {
                JSONObject jsonObject = contentJson.optJSONObject(JsonKey.EXTPARAMS);
                if (jsonObject != null) {
                    content.setVideoId(jsonObject.optString(JsonKey.VIDEOID));
                    content.setVideoType(jsonObject.optString(JsonKey.VIDEOTYPE));
                }
            }
            reply.addContent(content);
        }
        DBManager.getInstance()
                .insertReplyDetail(reply.getTopicId(), reply.getId(), parseReplyContentToHtml(contentArray));
    }

    public static List<SimpleData> parseSimpleDataList(JSONArray jsonArray) {

        List<SimpleData> profileList = new ArrayList<>();

        if (jsonArray == null || jsonArray.length() == 0) {
            return profileList;
        }
        JSONObject jsonObject;
        int length = jsonArray.length();
        for (int i = 0; i < length; i++) {
            jsonObject = jsonArray.optJSONObject(i);
            SimpleData simpleData = new SimpleData();
            simpleData.setType(jsonObject.optString(JsonKey.TYPE));
            simpleData.setTitle(jsonObject.optString(JsonKey.TITLE));
            simpleData.setData(jsonObject.optString(JsonKey.DATA));
            profileList.add(simpleData);
        }
        return profileList;
    }

    public static long parseLong(JSONObject jsonObject, String key) {
        String date = jsonObject.optString(key);
        return TextUtils.isEmpty(date) ? 0 : Long.valueOf(date);
    }

    public static String convertReplyContentToHtml(List<ReplyContent> replyContents) {
        if (replyContents != null && replyContents.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder(
                    "<body style=\"background-color:#fafafa;align:center\"><div style=\"max-width:100%\">");
            for (ReplyContent replyContent : replyContents) {
                switch (replyContent.getType()) {
                    case ReplyContent.TYPE_TEXT:
                        stringBuilder.append(handleText(replyContent.getInfo()));
                        break;
                    case ReplyContent.TYPE_INTERNAL_LINK:
                    case ReplyContent.TYPE_EXTERNAL_LINK:
                        stringBuilder.append(handleLink(replyContent.getUrl(), replyContent.getInfo()));
                        break;
                    case ReplyContent.TYPE_IMAGE:
                        stringBuilder.append(handleImage(replyContent.getOriginalInfo()));
                        break;
                    case ReplyContent.TYPE_VIDEO:
                        stringBuilder.append(handleVideo(replyContent.getInfo(), replyContent.getVideoType(), replyContent.getVideoId()));
                        break;
                    default:
                        stringBuilder.append(replyContent.getInfo());
                }
            }
            stringBuilder.append("</div></body></html>");
            return stringBuilder.toString();
        }
        return "<body></body>";
    }

    public static String parseReplyContentToHtml(JSONArray contentArray) {
        if (contentArray != null && contentArray.length() > 0) {
            StringBuilder stringBuilder = new StringBuilder(
                    "<body style=\"background-color:#fafafa;align:center\"><div style=\"max-width:100%\">");
            JSONObject contentJson;
            int size = contentArray.length();
            for (int i = 0; i < size; i++) {
                contentJson = contentArray.optJSONObject(i);
                switch (contentJson.optInt(JsonKey.TYPE)) {
                    case ReplyContent.TYPE_TEXT:
                        stringBuilder.append(handleText(contentJson.optString(JsonKey.INFOR)));
                        break;
                    case ReplyContent.TYPE_INTERNAL_LINK:
                    case ReplyContent.TYPE_EXTERNAL_LINK:
                        stringBuilder.append(handleLink(contentJson.optString(JsonKey.URL), contentJson.optString(JsonKey.INFOR)));
                        break;
                    case ReplyContent.TYPE_IMAGE:
                        stringBuilder.append(handleImage(contentJson.optString(JsonKey.ORIGINALINFO)));
                        break;
                    case ReplyContent.TYPE_VIDEO:
                        JSONObject jsonObject = contentJson.optJSONObject(JsonKey.EXTPARAMS);
                        String videoType = "", videoId = "";
                        if (jsonObject != null) {
                            videoType = jsonObject.optString(JsonKey.VIDEOTYPE);
                            videoId = jsonObject.optString(JsonKey.VIDEOID);
                        }
                        stringBuilder.append(handleVideo(contentJson.optString(JsonKey.INFOR), videoType, videoId));
                        break;
                    default:
                        stringBuilder.append(contentJson.optString(JsonKey.INFOR));
                }

            }
            stringBuilder.append("</div></body></html>");
            return stringBuilder.toString();
        }
        return "";
    }

    private static String handleText(String text) {
        text = text.replaceAll("\r\n", "<br/>").replace(" ", "&nbsp;");
        return handleExpress(text);
    }


    private static String handleExpress(String text) {
        if (TextUtils.isEmpty(text)) {
            return "<br/>";
        }
        StringBuilder stringBuilder = new StringBuilder("<div style=\"max-width:100%\">");
        int index = 0;
        Matcher locationMatcher = Pattern.compile("(?m)\\[mobcent_phiz=.*?\\]").matcher(text);
        while (locationMatcher.find()) {
            Matcher srcMatcher = Pattern.compile("http:(.*/)*/.*\\.\\w+").matcher(locationMatcher.group());
            if (srcMatcher.find()) {
                String imageHtml = "<img src=\"" + srcMatcher.group() + "\"/>";
                stringBuilder.append(text.substring(index, locationMatcher.start()))
                        .append(imageHtml);
                index = locationMatcher.end();
            }
        }
        stringBuilder.append(text.substring(index, text.length())).append("</div>");
        return stringBuilder.toString();
    }

    private static String handleLink(String href, String text) {
        if (TextUtils.isEmpty(text)) {
            return "<br/>";
        }
        if (TextUtils.isEmpty(href)) {
            return "<div style=\"max-width:100%\"><a href=\"" + text + "\">" + text + "</a></div>";
        } else {
            return "<div style=\"max-width:100%\"><a href=\"" + href + "\">" + text + "</a></div>";
        }
    }

    private static String handleImage(String src) {
        if (TextUtils.isEmpty(src)) {
            return "<br/>";
        }
        return "<div align=\"center\"><img onclick=\"showImage(this.getAttribute('src'))\" style=\"max-width:100%\" src=\"" + src + "\"/></div>";
    }

    private static String handleVideo(String src, String videoType, String videoId) {
        if (TextUtils.isEmpty(src)) {
            return "<br/>";
        }
        if (TextUtils.isEmpty(videoId) || Constants.VIDEO_UNKOWN.equals(videoType)) {
            return handleLink(src, src);
        }
        return "<div align=\"center\"><video controls=\"controls\" style=\"max-width:100%\" src=\"" + src + "\"/></div>";
    }

}
